package jp.wug.samples.cart;

import com.google.inject.Inject;
import com.google.inject.Provider;
import jp.wug.PageFlow;
import jp.wug.Renderer;

import java.util.LinkedHashMap;
import java.util.Map;

public class IndexPage {
    Map<String, Models.Product> products = new LinkedHashMap<String, Models.Product>();
    Models.Cart cart;
    Provider<CartPage> cartPageProvider;
    Provider<PageFlow> pageFlowProvider;

    @Inject
    public IndexPage(Models.Cart cart, Provider<CartPage> cartPageProvider, Provider<PageFlow> pageFlowProvider) {
        this.cart = cart;
        this.cartPageProvider = cartPageProvider;
        this.pageFlowProvider = pageFlowProvider;

        addProduct(new Models.Product(1, "Product1"));
        addProduct(new Models.Product(2, "Product2"));
        addProduct(new Models.Product(3, "Product3"));
        addProduct(new Models.Product(4, "Product4"));
        addProduct(new Models.Product(5, "Product5"));
    }

    private void addProduct(Models.Product product) {
        products.put(product.getKey(), product);
    }

    public void renderProducts(Renderer<String, ProductView> renderer) {
        for (Map.Entry<String, Models.Product> entry : products.entrySet()) {
            renderer.render(entry.getKey(), new ProductView(entry.getValue()));
        }
    }

    public ProductView getProduct(String key) {
        return new ProductView(products.get(key));
    }

    public class ProductView {
        Models.Product product;

        ProductView(Models.Product product) {
            this.product = product;
        }

        public String getName() {
            return product.getName();
        }

        public void addToCart() {
            cart.add(product);
            PageFlow pageFlow = pageFlowProvider.get();
            pageFlow.redirectTo(CartPage.class, cartPageProvider.get());
        }
    }
}
